<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 警告框 -->
      <el-alert
        title="注意！只允许为第三级分类添加参数！"
        type="warning"
        show-icon
      >
      </el-alert>
      <div class="cascader">
        <span>选择商品分类:</span>
        <!-- 级联选择器 -->
        <el-cascader
          v-model="checkedKeys"
          :options="catesList"
          :props="props"
          @change="handleChange"
        ></el-cascader>
      </div>

      <!-- 标签页 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="first">
          <el-button
            type="primary"
            size="mini"
            @click="showAddParam"
            :disabled="checkedKeys.length !== 3"
            >添加参数</el-button
          >

          <!-- 表格 -->
          <el-table :data="manyTableList" style="width: 100%" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(tag, index) in scope.row.attr_vals.trim().length === 0
                    ? []
                    : scope.row.attr_vals.trim().split(' ')"
                  :key="index"
                  closable
                  type="primary"
                  @close="handleClose(scope.row, tag)"
                >
                  {{ tag }}
                </el-tag>

                <!-- 动态添加tag -->
                <el-input
                  class="input-new-tag"
                  v-if="inputVisible"
                  v-model="inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>

            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="动态参数">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="small"
                  @click="showEditParam(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="small"
                  @click="deleteParam(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="second">
          <el-button
            type="primary"
            size="mini"
            @click="showAddParam"
            :disabled="checkedKeys.length !== 3"
            >添加参数</el-button
          >

          <!-- 表格 -->
          <el-table :data="manyTableList" style="width: 100%" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(tag, index) in scope.row.attr_vals.trim().length === 0
                    ? []
                    : scope.row.attr_vals.trim().split(' ')"
                  :key="index"
                  closable
                  type="primary"
                  @close="handleClose(scope.row, tag)"
                >
                  {{ tag }}
                </el-tag>

                <!-- 动态添加tag -->
                <el-input
                  class="input-new-tag"
                  v-if="inputVisible"
                  v-model="inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>

            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="动态参数">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="small"
                  @click="showEditParam(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="small"
                  @click="deleteParam(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数的对话框 -->
    <el-dialog
      :title="'添加' + addType"
      :visible.sync="addDialogVisible"
      width="50%"
    >
      <!-- 表单 -->
      <el-form
        :model="attributes"
        :rules="attributesRules"
        ref="attributesRef"
        label-width="100px"
      >
        <el-form-item :label="addType" prop="attr_name">
          <el-input v-model="attributes.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParamData">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑参数的对话框 -->
    <el-dialog
      :title="'编辑' + addType"
      :visible.sync="editDialogVisible"
      width="50%"
    >
      <!-- 表单 -->
      <el-form
        :model="attributes"
        :rules="attributesRules"
        ref="editAttributesRef"
        label-width="100px"
      >
        <el-form-item :label="addType" prop="attr_name">
          <el-input v-model="attributes.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParamData">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Parems",
  data() {
    return {
      //   参数列表
      paramsList: [],
      //   分类参数 ID
      cat_id: "",
      //   动态参数列表
      manyTableList: [],
      // 商品分类列表
      catesList: [],
      // 选中的id数组
      checkedKeys: [],
      props: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
      },
      //   绑定值，选中选项卡的 name
      activeName: "first",
      //   是否开启input
      inputVisible: false,
      inputValue: "",
      attr_vals: [],
      // 添加参数的信息
      attributes: {
        attr_name: "",
        attr_sel: "",
        attr_vals: "",
      },
      attributesRules: {
        attr_name: [
          {
            required: true,
            message: "请输入参数",
            trigger: "blur",
          },
        ],
      },
      addDialogVisible: false,
      // 编辑参数
      editDialogVisible: false,
      // 属性 ID
      attr_id: "",
    };
  },
  created() {
    this.getCatesList();
  },
  methods: {
    //   获取参数列表
    async getParamsList() {
      const { data: res } = await this.$http.get(
        `categories/${this.cat_id}/attributes`,
        {
          params: { sel: this.isMany },
        }
      );
      if (res.meta.status !== 200) return;
      this.manyTableList = res.data;
    },
    async getCatesList() {
      const { data: res } = await this.$http.get(`categories`);
      if (res.meta.status !== 200) return this.$message.error("获取列表失败2");
      this.catesList = res.data;
    },
    // 级联选择器发生变化
    handleChange() {
      if (this.checkedKeys.length !== 3) {
        this.checkedKeys = [];
        this.cat_id = "";
        return;
      }
      this.cat_id = this.checkedKeys[2];
      this.getParamsList();
    },
    // 点击标签页
    handleClick() {
      this.getParamsList();
    },
    // 失去焦点处理
    async handleInputConfirm(row) {
      this.inputVisible = false;

      //   如果输入了值
      if (this.inputValue.trim() !== "") {
        this.attr_vals = row.attr_vals.split(" ");
        this.attr_vals.push(this.inputValue);
        //   添加到服务器
        const { data: res } = await this.$http.put(
          `categories/${this.cat_id}/attributes/${row.attr_id}`,
          {
            attr_name: row.attr_name,
            attr_sel: "many",
            attr_vals: this.attr_vals.join(" "),
          }
        );
        if (res.meta.status !== 200) return this.$message.error("更新失败");

        this.$message.success("更新成功");
        row.attr_vals = this.attr_vals.join(" ");
        this.inputValue = "";
      } else {
        this.inputValue = "";
      }
    },
    // 显示input
    showInput() {
      this.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // 删除参数
    async handleClose(row, tag) {
      const arr = row.attr_vals.split(" ");
      const x = arr.findIndex((x) => x === tag);
      arr.splice(x, 1);
      row.attr_vals = arr.join(" ");

      //   添加到服务器
      const { data: res } = await this.$http.put(
        `categories/${this.cat_id}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: "many",
          attr_vals: row.attr_vals,
        }
      );
      if (res.meta.status !== 200) return this.$message.error("更新失败");

      this.$message.success("更新成功");
    },
    // 开启添加参数对话框
    showAddParam() {
      this.addDialogVisible = true;
      this.attributes.attr_sel = this.isMany;
    },
    // 添加参数
    addParamData() {
      this.$refs.attributesRef.validate(async (valid) => {
        if (!valid) return this.$message.error("请输入参数");

        const { data: res } = await this.$http.post(
          `categories/${this.cat_id}/attributes`,
          this.attributes
        );
        if (res.meta.status !== 201) return this.$message.error("创建失败");
        this.$message.success("创建成功");
        this.addDialogVisible = false;
        this.getParamsList();
      });
    },
    // 开启编辑参数的对话框
    showEditParam(row) {
      this.editDialogVisible = true;
      this.attr_id = row.attr_id;
      this.attributes.attr_name = row.attr_name;
      this.attributes.attr_sel = row.attr_sel;
      this.attributes.attr_vals = row.attr_vals;
    },
    // 编辑参数
    editParamData() {
      this.$refs.editAttributesRef.validate(async (valid) => {
        if (!valid) return this.$message.error("请填写参数");

        const { data: res } = await this.$http.put(
          `categories/${this.cat_id}/attributes/${this.attr_id}`,
          this.attributes
        );
        if (res.meta.status !== 200) return this.$message.error("更新失败");
        this.$message.success("更新成功");
        this.editDialogVisible = false;
        this.getParamsList();
      });
    },
    // 删除参数
    async deleteParam(row) {
      const confirmStr = await this.$confirm(
        "此操作将永久删除该参数, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmStr !== "confirm")
        return this.$message.info("您取消了删除操作");

      const { data: res } = await this.$http.delete(
        `categories/${this.cat_id}/attributes/${row.attr_id}`
      );
      if (res.meta.status !== 200) return this.$message.error("删除失败");

      this.$message.success("删除成功");
      this.getParamsList();
    },
  },
  computed: {
    addType() {
      return this.activeName === "first" ? "动态参数" : "静态属性";
    },
    isMany() {
      return this.activeName === "first" ? "many" : "only";
    },
  },
};
</script>

<style scoped>
.cascader {
  margin-top: 15px;
}
.cascader span {
  margin-right: 15px;
}
.input-new-tag {
  width: 120px;
}
</style>